<template>
  <div class="pf-callback">
    <div class="pf-flex pf-jc-center pf-mb-30" style="height: 100%" v-loading="logining > -1">
      <img class="pf-vertical-middle" style="height: 3em; width: 5em" :src="logo" />
      <span class="pf-fs-20 pf-lh-50 pf-ml-30 pf-nowrap">DCMS</span>
      <span v-if="logining === 0">登录中，请稍后··· </span>
      <span v-else-if="logining === 1">菜单初始化，请稍后··· </span>
      <div v-else>
        Ops! 好像有点问题，<el-button link type="primary" @click="reEnter">重新访问下呢</el-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { Constants } from '@/constants/constants';
import router from '@/router';
import { useNotice } from '@/components/element-plus/notice';
import { useAuth } from 'pf-component';
import { useStore } from 'vuex';
import { initByToken } from '@/constants/util/init';

export default defineComponent({
  name: 'Callback',
  setup() {
    const logo = require('@/assets/images/logo.png');
    const logining = ref(0);
    const route = useRoute();
    const store = useStore();
    const initToken = () => {
      if (route.query.code) {
        useAuth()
          .token(route.query)
          .then(res => {
            logining.value = 1;
            if (res) {
              initByToken().then(res => {
                if (res) {
                  const index = store.getters['menus/index'];
                  if (index) {
                    router.replace({ name: index.menuCode });
                  } else {
                    throw new Error('无应用权限');
                  }
                } else {
                  throw new Error('用户初始化失败');
                }
              });
            } else {
              throw new Error('获取token失败');
            }
          })
          .catch(err => {
            useNotice().message.error(err?.toString() || '操作失败');
            logining.value = -1;
          });
      } else {
        useNotice().message.error('授权码参数缺失');
        logining.value = -1;
      }
    };
    const reEnter = () => {
      useAuth().clearCache();
      location.href = '/';
    };
    onMounted(() => {
      initToken();
    });
    return {
      logo,
      logining,
      initToken,
      reEnter
    };
  }
});
</script>

<style scoped lang="scss">
.#{$prefix} {
  &-callback {
    height: 100vh;
  }
}
</style>
